package com.yiming.shiro.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.yiming.shiro.repository.RoleRepository;
import com.yiming.shiro.repository.UserRepository;
import com.yiming.shiro.repository.entity.Role;
import com.yiming.shiro.repository.entity.User;
import com.yiming.shiro.service.dto.RoleDTO;
import com.yiming.shiro.service.dto.UserDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
@Transactional(propagation = Propagation.REQUIRED)
public class UserServiceImpl implements UserService {
    @Autowired
    private RoleRepository roleRepository;

    @Autowired
    private UserRepository userRepository;

    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public List<RoleDTO> getRoleListByName(String name) {
        final List<Role> roleList = roleRepository.findRoleByUserName(name);
        if (CollectionUtil.isEmpty(roleList)) {
            return new ArrayList<>();
        }
        return roleList.stream().map(role -> {
            RoleDTO roleDTO = RoleDTO.builder().build();
            BeanUtil.copyProperties(role, roleDTO);
            return roleDTO;
        }).collect(Collectors.toList());
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public Optional<UserDTO> findUserByName(String name) {
        User user = userRepository.findFirstByNameAndActiveTrue(name);
        if (user == null) {
            return Optional.empty();
        }
        UserDTO userDTO = UserDTO.builder().build();
        BeanUtil.copyProperties(user, userDTO);
        return Optional.of(userDTO);
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public List<UserDTO> getAllValidUsers() {
        List<User> userList = userRepository.findAllByActiveTrue();
        if (CollectionUtil.isEmpty(userList)) {
            return new ArrayList<>();
        }
        return userList.stream().map(user -> {
            UserDTO userDTO = UserDTO.builder().build();
            BeanUtil.copyProperties(user, userDTO);
            return userDTO;
        }).collect(Collectors.toList());
    }
}
